<template>
  <app-dialog-form
    title="回复内容"
    :confirm="handleSubmit"
    :width="520"
    @closed="handleDialogClosed"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="0px"
    >
      <el-form-item
        label=""
        prop="content"
      >
        <el-input
          v-model="formData.content"
          :autosize="{ minRows: 4, maxRows: 8 }"
          type="textarea"
        />
      </el-form-item>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { PropType } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import { setProductReply } from '@/api/product'

const props = defineProps({
  id: {
    type: Number as PropType<number | null>,
    default: null
  }
})

interface EmitsType {
  (e: 'update:id', value: number | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const formData = ref({
  content: ''
})

const formRules: IFormRule = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' }
  ]
}

const handleDialogClosed = () => {
  emit('update:id', null)
  form.value?.clearValidate() // 清除验证结果
  form.value?.resetFields() // 清除表单数据
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  if (!props.id) return ElMessage.error('缺少参数id')
  await setProductReply(props.id, formData.value)
  emit('success')
  ElMessage.success('回复成功')
}
</script>

<style lang="scss" scoped>
</style>
